<template>
  <div class="areaContainer">
    <div class="search">
      <el-input v-model.trim="searchValue" placeholder="请输入区域位置关键字进行查询" clearable :prefix-icon="Search" @keyup="getAreaList(searchValue)">
        <template #append>
          <el-button :icon="Search"  @click="getAreaList(searchValue)"/>
        </template>
      </el-input>
      <el-button style="margin-left: 30px;" type="primary" @click="addAreaVisable = true">新建停车场</el-button>
      <el-dialog v-model="addAreaVisable" title="添加停车场" width="30%" draggable>
        <el-form v-model="addAreaForm" label-position="right">
          <el-form-item prop="区域名称" label="区域所在校区">
             <el-select v-model="addAreaForm.name" placeholder="请选择区域名称">
               <el-option label="西区" value="西区" />
               <el-option label="北区" value="北区" />
               <el-option label="东区" value="东区" />
             </el-select>
          </el-form-item>
          <el-form-item prop="categoryName" label="停   车   类   型">
            <el-select v-model="addAreaForm.categoryName" placeholder="请选择区域名称">
               <el-option label="自行车" value="自行车" />
               <el-option label="电瓶车" value="电瓶车" />
             </el-select>
          </el-form-item>
          <el-form-item prop="location"  width="100" label="区域具体位置">
            <el-input v-model="addAreaForm.location" placeholder="请输入区域位置"  width="150"/>
          </el-form-item>
          <el-form-item prop="总车位数"  width="100" label="可停车位总数">
            <el-input v-model.number="addAreaForm.parkingNumber" placeholder="请输入总车位数"/>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="addAreaVisable = false">取消</el-button>
            <el-button type="primary" @click="addArea()">确认</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
    <el-table :data="areaData" stripe style="width: 100%;margin-top: 10px;" height="50%">
    <el-table-column prop="areaId" label="区域ID" width="85"/>
    <el-table-column prop="name" label="区域名称" width="110"  :filters="nameFilter" :filter-method="filterHandler1"/>
    <el-table-column prop="location" label="区域位置" width="250"/>
    <el-table-column prop="categoryName" label="停放车辆类型"  :filters="categoryNameFilter" :filter-method="filterHandler2"/>
    <el-table-column prop="parkingNumber" label="总车位数" />
    <el-table-column prop="freeNumber" label="空闲车位数" />
    <el-table-column fixed="right" label="操作" width="130">
      <template #default="row">
          <el-tooltip content="编辑" placement="bottom">
            <el-button link type="primary" :icon="Edit"  class="myLink" @click="clickEditHandler(row)" />
          </el-tooltip>
          <el-tooltip content="删除" placement="bottom">
            <el-button link type="danger" :icon="Delete"  class="myLink" @click="areaDelete(row)"></el-button>
          </el-tooltip>
      </template>
    </el-table-column>
  </el-table>
  <el-dialog v-model="editAreaVisible" title="编辑" draggable>
    <el-form :model="editAreaForm" label-width="80px">
      <el-form-item label="区域ID" prop="areaId">
        <el-input v-model="editAreaForm.areaId" autocomplete="off" disabled/>
      </el-form-item>
      <el-form-item label="区域名称" prop="name">
        <el-input v-model="editAreaForm.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="区域位置" prop="location">
        <el-input v-model="editAreaForm.location" autocomplete="off" />
      </el-form-item>
      <el-form-item label="停放车辆类型" prop="categoryName">
        <el-input v-model="editAreaForm.categoryName" placeholder="填写“自行车”或者“电动车”" autocomplete="off" />
      </el-form-item>
      <el-form-item label="总车位数" prop="parkingNumber">
        <el-input v-model.number="editAreaForm.parkingNumber" autocomplete="off" />
      </el-form-item>
      <el-form-item label="空闲车位数" prop="freeNumber">
        <el-input v-model.number="editAreaForm.freeNumber" autocomplete="off" disabled/>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="editAreaVisible = false">取消</el-button>
        <el-button type="primary" @click="areaEdit()">提交修改</el-button>
      </span>
    </template>
  </el-dialog>
   <div class="pagination">
    <el-pagination v-model:current-page="page" v-model:page-size="size" :page-sizes="[5,10,20,30]" :small="small" :disabled="disabled"
      :background="background" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
  </div>
  </div>
</template>

<script setup>
import { reactive , inject , onMounted , ref } from "vue"
import axios from '../../axios/axiosInstance'
import { ElLoading,ElMessage ,ElMessageBox} from 'element-plus'
import { Delete ,Edit,Search} from '@element-plus/icons-vue'

//变量定义
let editAreaVisible = ref(false)
let addAreaVisable = ref(false)
let areaData = reactive([])
let nameFilter = reactive([])
let categoryNameFilter = reactive([])
let searchValue = ref()
let editAreaForm = reactive({
  areaId: 0,
  name: '',
  location: '',
  categoryName: '',
  parkingNumber: 0,
  freeNumber: 0,
})

let addAreaForm = reactive({
  name: '',
  location: '',
  categoryName: '',
  parkingNumber: 0,
  freeNumber: 0,
})
const total = ref(0)
let page = 1
let size = 5
const small = ref(false)
const background = ref(false)
const disabled = ref(false)

//方法 

const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
  size = val
  init()
}
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  page = val
  init()
}

 const clear = (value) => {
    Object.keys(value).map(key => {
      delete value[key]
    })
  }

const getAreaList = (searchValue) => {
  if(searchValue != ''){
    axios.get(`/parking-service/area/areaList/${searchValue}`).then((res) => {
        console.log(res)    
        if(res.code == 200){
          clear(areaData)
          for(let i in res.data){
            console.log(i)
            areaData.push(res.data[i])
          }
          ElMessage({type: "success",message: "查询成功"});
        }else{
          ElMessage({type: "error",message: "查询失败"});
       }
      }).catch((err) => {
        console.log(err)
      })
  }else{
    init()
  }
}
const filterHandler1 = (value,row,column) => {
  const property = column['property']
  return row[property] === value
}

const filterHandler2 = (value,row,column) => {
  const property = column['property']
  return row[property] === value
}

const addArea = () =>{
  //向后端发送请求
   axios.post('/parking-service/area/addArea/',addAreaForm).then((res) => {   
      console.log("res为：")
      console.log(res)
      if(res.code == 200){
          //添加停车区域成功
          ElMessage({type: "success",message: "添加成功"});
          areaData.push(res.data)
        }else{
          //添加失败
         ElMessage({type: "error",message: "添加失败"})
        }
    
    }).catch((err) => {

      console.log(err)

    })

}

const clickEditHandler = (row) => {
  editAreaVisible.value = true;
  console.log("row为：")
  console.log(row)
  editAreaForm.areaId = row.row.areaId;
  editAreaForm.name = row.row.name;
  editAreaForm.location = row.row.location;
  editAreaForm.categoryName = row.row.categoryName;
  editAreaForm.parkingNumber = row.row.parkingNumber;
  editAreaForm.freeNumber = row.row.freeNumber;
  console.log(editAreaForm)
}

const areaEdit = () => {
   axios.delete('/parking-service/area/'+row.row.areaId).then((res) => {
    console.log(res)
    if(res.code == 200){
      ElMessage({type: "success",message: "删除成功"});
      areaData.pop(row.$index)
    }else{
      ElMessage({type: "error",message: "删除失败"});
    }
  }).catch((err) => {
    console.log(err)
  })
}

const areaDelete = (row) => {
  console.log("删除的row为：")
  console.log(row)
  let location = row.row.location
  ElMessageBox.confirm(
    '确定要删除停车场'+location+'吗？',
    'Warning',
    {
      confirmButtonText: 'OK',
      cancelButtonText: 'Cancel',
      type: 'warning',
    }
  )
    .then(() => {
      let areaId = row.row.areaId;
      console.log(areaId)
      axios.delete('/parking-service/area/'+areaId).then((res) => {
        console.log(res)
        if(res.code == 200){
          ElMessage({type: "success",message: "删除成功"});
          areaData.pop(row.$index)
        }else{
          ElMessage({type: "error",message: "删除失败"});
       }
      }).catch((err) => {
        console.log(err)
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '删除取消',
      })
    }) 
}

const init = () => {
  const loading = ElLoading.service({
        lock: true,
        text: '拼命加载中',
          background: 'rgba(0, 0, 0, 0.7)',
      })
      setTimeout(() => {
        loading.close()
      }, 2000)
     axios.get(`/parking-service/area/areaList/${page}/${size}`).then((res) => {   
      console.log("res为：")
      console.log(res)
      clear(areaData)
      total.value = res.data.total
      for(let i in res.data.content){
        console.log(i)
        areaData.push(res.data.content[i])
      }
      console.log("最后的areaData是：")
      console.log(areaData)
    }).catch((err) => {

      console.log(err)

    })
}

const getNameFilter = () => {
   axios.get('/parking-service/area/areaName').then((res) => {   
      console.log("res为：")
      console.log(res)
      console.log(total)
      for(let i in res.data){
        console.log(i)
        nameFilter.push(res.data[i])
      }
      console.log("最后的parkingData是：")
      console.log(nameFilter)
    }).catch((err) => {

      console.log(err)

    })
}

const getCategoryNameFilter = () => {
   axios.get('/parking-service/category/categoryName').then((res) => {   
      console.log("res为：")
      console.log(res)
      console.log(total)
      for(let i in res.data){
        console.log(i)
        categoryNameFilter.push(res.data[i])
      }
      console.log("最后的parkingData是：")
      console.log(categoryNameFilter)
    }).catch((err) => {

      console.log(err)

    })
}

//页面初始化方法
onMounted(()=>{ 
  init()
  getNameFilter()
  getCategoryNameFilter()
})
</script>

<style scoped>
.areaContainer .search{
  display: flex;
  width: 600px;
}
.areaContainer .pagination{
 justify-content: center;
 margin-top: 15px;
}

</style>
